package com.example.word.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.dict.R;
import com.example.word.bean.Browse;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.Word;
import com.example.word.ui.activity.BrowseActivity;
import com.example.word.ui.activity.LoginActivity;
import com.example.word.ui.activity.StudyPlanActivity;
import com.example.word.ui.activity.UnitActivity;
import com.example.word.ui.activity.WordReviewActivity;
import com.example.word.ui.activity.WordStudyActivity;
import com.example.word.util.AlwaysMarqueeTextView;
import com.example.word.util.CommonUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 首页Fragment
 */
public class StudyFragment extends Fragment {
    private Activity myActivity;
    private Boolean mIsAdmin;
    private boolean iscbAll = false;
    private List<Dict> mDict = new ArrayList<>();
    private String account;
    private Button startStudy;
    private TextView editDict, reviewCount, todayCount, totalCount, currentUserDict, dictStudyCount;
    private AlwaysMarqueeTextView systemMsg;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        myActivity = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_study, container, false);
        //获取控件
        startStudy = view.findViewById(R.id.startStudy);
        // 设置按钮主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            startStudy.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            startStudy.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
        editDict = view.findViewById(R.id.editDict);
        dictStudyCount = view.findViewById(R.id.dictStudyCount);
        reviewCount = view.findViewById(R.id.reviewCount);
        todayCount = view.findViewById(R.id.todayCount);
        totalCount = view.findViewById(R.id.totalCount);
        currentUserDict = view.findViewById(R.id.currentUserDict);
        systemMsg = view.findViewById(R.id.systemMsg);

//        reviewCount.setPaintFlags(reviewCount.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
//        todayCount.setPaintFlags(todayCount.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
//        totalCount.setPaintFlags(totalCount.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        currentUserDict.setPaintFlags(currentUserDict.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        initView();
        return view;
    }

    private void initView() {
        mIsAdmin = (Boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        loadData();//加载数据

        //开始学习
        startStudy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 如果当前词汇的单词未下载，先进行下载
                String currentUserDictTitle = currentUserDict.getText().toString();
                Dict dict = Dict.where("title = ? ", currentUserDictTitle).findFirst(Dict.class);
                if (dict == null) {
                    MessageUtils.show("当前词汇不存在，请切换词汇", myActivity);
                    return;
                }
                // 判断是否已经下载过
                ProgressDialog dialog = new ProgressDialog(myActivity);
                dialog.setMessage("正在加载词库单词···");
                dialog.show();
                if (!"downloaded".equals(dict.getWordFileUrl())) {
                    // 去有道词典下载词汇
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            // 开始远程下载
                            // saveWord(dict.getWordFileUrl(), dict.getTitle());
                            OkHttpClient client = new OkHttpClient();
                            Request request = new Request.Builder().url(dict.getWordFileUrl()).build();

                            client.newCall(request).enqueue(new Callback() {
                                @Override
                                public void onResponse(Call call, Response response) {
                                    if (response.isSuccessful()) {
                                        // 创建目标文件夹
                                        // 获取应用的私有目录
                                        File folder = myActivity.getExternalFilesDir(null);
                                        // 保存下载的ZIP文件
                                        File zipFile = new File(folder, dict.getTitle() + ".zip");
                                        try (OutputStream outputStream = new FileOutputStream(zipFile)) {
                                            outputStream.write(response.body().bytes());
                                        } catch (Exception e) {
                                            com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                                        }

                                        // 解压缩ZIP文件
                                        try {
                                            int wordCount = 0;
                                            List<Word> saveWords = new ArrayList<>(dict.getWordNumber());
                                            try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile))) {
                                                ZipEntry zipEntry;

                                                while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                                                    if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".json")) {
                                                        // Read JSON content line by line
                                                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                                        byte[] buffer = new byte[1024];
                                                        int bytesRead;

                                                        while ((bytesRead = zipInputStream.read(buffer)) != -1) {
                                                            baos.write(buffer, 0, bytesRead);
                                                        }

                                                        byte[] data = baos.toByteArray();
                                                        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data)))) {
                                                            String line;
                                                            while ((line = reader.readLine()) != null) {
                                                                wordCount++;
                                                                // Process each line of JSON content
                                                                JSONObject jsonWord = new JSONObject(line);
                                                                Log.d("单词行" + wordCount, line);
                                                                // HomeFragment.buildSaveWord(jsonWord, dict.getTitle());
                                                                saveWords.add(HomeFragment.buildSaveWord(jsonWord, dict.getTitle()));
                                                                try {
                                                                    dialog.setMessage(String.format("正在下载单词(%s/%s)···", wordCount, dict.getWordNumber()));
                                                                } catch (Exception e) {
                                                                }
                                                            }

                                                            Word.saveAll(saveWords);
                                                        }
                                                    }
                                                }
                                            }

                                            // 下载完成之后清除文件地址
                                            dict.setWordFileUrl("downloaded");
                                            dict.setWordNumber(saveWords.size());
                                            dict.save();
                                            startStudyActivity(dict, dialog);
                                        } catch (Exception e) {
                                            com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                                            MessageUtils.show("解析单词信息出现错误 " + e.getMessage(), myActivity);
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(Call call, IOException e) {
                                    com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                                }
                            });
                        }
                    }, 1005);
                } else {
                    startStudyActivity(dict, dialog);
                }
            }
        });

        //切换词汇
        editDict.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 根据单元（页数），和总数进行查询
                Intent intent = new Intent(myActivity, StudyPlanActivity.class);
                startActivityForResult(intent, 100);
            }
        });

        // 点击今日新词
        todayCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(myActivity, BrowseActivity.class);
                startActivity(intent);
            }
        });

        // 点击总计学习
        totalCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(myActivity, BrowseActivity.class);
                startActivity(intent);
            }
        });

        // 点击待复习
        reviewCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(myActivity, WordReviewActivity.class);
                startActivity(intent);
            }
        });
    }

    private void startStudyActivity(Dict dict, ProgressDialog dialog) {
        // 根据单元（页数），和总数进行查询
        Intent intent = new Intent(myActivity, WordStudyActivity.class);

        // 查询出当前词汇用户已学习的单词

        String dayTaskString = String.valueOf(StudyPlan.where("account = ?", account).findFirst(StudyPlan.class).getDayTask());

        List<Word> wordList;
        List<Browse> browseList = Browse.where("account = ?", account).find(Browse.class);
        if (!browseList.isEmpty()) {
            StringBuilder wordsWhere = new StringBuilder();
            for (Browse word : browseList) {
                wordsWhere.append("'").append(word.getWord().replace("'", "''")).append("',");
            }
            String inSql = wordsWhere.toString().substring(0, wordsWhere.toString().length() - 1);
            wordList = Word.where("dict = ? and word not in (" + inSql + ")", dict.getTitle()).limit(Integer.parseInt(dayTaskString)).offset(0).find(Word.class);
        } else {
            wordList = Word.where("dict = ?", dict.getTitle()).limit(Integer.parseInt(dayTaskString)).offset(0).find(Word.class);
        }
        List<String> wordArray = new ArrayList<>();
        for (Word word : wordList) {
            wordArray.add(word.getWord());
        }
        intent.putExtra("wordArray", wordArray.toArray(new String[0]));
        intent.putExtra("dict", dict.getTitle());
        dialog.dismiss();
        startActivityForResult(intent, 100);
    }

    /**
     * 加载数据
     */
    private void loadData() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 加载当前用户学习情况 dayTask,todayCount,totalCount, currentUserDict;
                StudyPlan studyPlan = StudyPlan.queryCurrentUserPlan(account);

                reviewCount.setText(String.valueOf(studyPlan.getReviewCount()));
                todayCount.setText(String.valueOf(studyPlan.getTodayCount()));
                totalCount.setText(String.valueOf(studyPlan.getTotalCount()));
                currentUserDict.setText(studyPlan.getDict());
                // 查询当前词汇单词学习了多少个
                List<Word> wordList = Word.where("dict = ?", studyPlan.getDict()).find(Word.class);
                List<Browse> browseList = Browse.where("account = ?", account).find(Browse.class);
                int commonWordCount = CommonUtils.countCommonWords(wordList, browseList, Word::getWord, Browse::getWord);
                // List<Dict> dictList = Dict.where("title = ? ", studyPlan.getDict()).find(Dict.class);
                dictStudyCount.setText("(" + commonWordCount + " / " + wordList.size() + ")");

                systemMsg.setText(String.format("系统消息: 您今日学习目标为%s个单词，今日已学习%s个单词，累计学习了%s个单词，继续加油噢！", studyPlan.getDayTask(), studyPlan.getTodayCount(), studyPlan.getTotalCount()));

            }
        }, 1);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            loadData();
        }
    }

    public void setColor() {
        // 设置按钮主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            startStudy.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            startStudy.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
    }

}
